<template>
  <div>
    <div>
      <div class="container">
        <el-upload
          class="cover-uploader"
          :show-file-list="false"
          :action="uploadUrl"
          :headers="headers"
          :on-success="handleCoverSuccess"
          :before-upload="beforeUpload">
          <img v-if="coverUrl" :src="coverUrl" class="cover" alt="">
          <i v-else class="el-icon-plus cover-uploader-icon"></i>
        </el-upload>

        <div class="input-1">
          <div class="label">视频名称:</div>
          <el-input v-model="videoName"></el-input>
        </div>
      </div>
      <p class="des">请上传封面</p>
    </div>
    <div>
      <div>
          <el-upload
            class="video"
            drag
            action="/"
            :multiple = "false"
            :limit="1"
            :http-request="uploadFile"
            :before-upload="beforeUploadVideo"
            :on-success="handleVideoSuccess"
            >
            <el-icon class="el-icon--upload"></el-icon>
            <div class="el-upload__text">
              请拖拽文件到此处或 <em>点击此处上传视频</em>
            </div>
          </el-upload>
      </div>
    </div>
  <el-button class="vbutton"type="primary" @click="submit">发布视频</el-button>
  </div>

</template>

<script>
import {getToken} from "@/utils/auth";
import {checkFile, fileLoad, getSlice, initTask, test, testImg, uploadSliceOne} from "@/api/video/upload";
import md5 from "@/utils/md5";
import {addVideo} from "@/api/video/video";

export default {
  data() {
    return {
      now:null,
      videoName:'',
      fileMd5:'',
      coverUrl: '',
      videoUrl:'',
      uploadUrl:  process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
    };
  },
  methods: {
    submit(){
      if(this.videoUrl===""){
        this.$message.error('视频文件不能为空')
        return
      }
      if(this.videoName===""){
        this.$message.error('视频名字不能为空')
        return
      }
      if(this.coverUrl===""){
        this.$message.error('视频封面不能为空')
        return
      }
      addVideo(this.coverUrl,this.videoUrl,this.videoName).then(
        res =>{
            this.coverUrl = ""
            this.videoUrl = ""
            this.videoName = ""
        }

      )
      this.$message.success('发布成功')
    },
   async uploadFile(params) {
      console.log("uploadFile", params);
      const file = params.file;
      console.log(file.type)
     const formData = new FormData();
        formData.append("file", params.file);
         fileLoad(formData).then(
          res=>{
            this.videoUrl = res.data.url
            console.log(res.data)
          }
        )
     //  const md5S = await md5(file)
     //  this.fileMd5 = md5S
     //  console.log(md5S)
     //  //秒传，如果上传的视频已经存在
     //  if(this.check(md5S)!==false){
     //    this.$message.success('上传成功!');
     //    return;
     //  }
     // console.log("test")
     //  //如果不是大文件，直接上传
     //  const NoSliceSize = file.size / 1024 / 1024 < 50;
     //  if (NoSliceSize) {
     //    const formData = new FormData();
     //    formData.append("file", params.file);
     //    testImg(formData).then(
     //      res=>{
     //        this.videoUrl = res.data.url
     //        this.$message.success('上传成功!');
     //      }
     //    )
     //    return;
     //  }
     //  ////======
     //    const chunkSize = 50*1024*1024;
     //    const totalSize = file.size;
     //    const chunkNum = Math.ceil(totalSize / chunkSize);
     //    console.log(chunkNum+"sadasdad")
     //    //查看该文件是否在上传了一部分(续传)
     //     getSlice(md5S).then(
     //      res=>{
     //        console.log(res.data)
     //        this.now = res.data
     //      }
     //    )
     //    if(this.now==null){
     //      console.log(totalSize)
     //      initTask(md5S,chunkSize,chunkNum,file.size);
     //    }
     //    this.uploadSlice(file)
    },

     check(md5S){
       checkFile(md5S).then(
         res =>{
             this.videoUrl = res.data
            console.log(res.data)
         }
       )
       return this.videoUrl !== "";
     },
      uploadSlice(file){
      const sliceSize = 200;
      const fileSize = file.size / 1024 / 1024; // 获取文件的总大小
        console.log(fileSize)
      const sliceNum = Math.ceil(fileSize / sliceSize); // 计算分片数量
      const fileSlices = new Map(); // 创建一个 Map 对象来存储分片
      for (let i = 0; i < sliceNum; i++) {
        console.log("slice"+i)
        const start = i * sliceSize;
        const end = Math.min(start + sliceSize, fileSize); // 避免超出文件大小
        const slice = file.slice(start, end); // 使用 File API 的 slice 方法获取分片
        fileSlices.set(i, slice); // 将分片存入 Map 对象，key 为分片编号，value 为分片内容
        if(i>=this.now){
          uploadSliceOne(i,slice)
        }
      }
      return fileSlices
    },
    handleCoverSuccess(response) {
      this.coverUrl = response.data.url
      console.log(this.coverUrl)
    },
    handleVideoSuccess(){
      this.$message.success("上传成功")
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 5;
      console.log(this.uploadUrl)
      if (!(isJPG || isPNG)) {
        this.$message.error('上传封面图片只能是 JPG 或者 PNG 格式!');
        return false; // 阻止文件上传
      }
      if (!isLt2M) {
        this.$message.error('上传封面图片大小不能超过 5MB!');
        return false; // 阻止文件上传
      }
      return true; // 允许文件上传
    },
    beforeUploadVideo(file) {
      const isMp4 = file.type === 'video/mp4';
      const isMvn = file.type === 'video/mvn';
      console.log(this.uploadUrl)
      if (!(isMp4 || isMvn)) {
        this.$message.error('上传文件只能是 mp4 或者 mvn 格式!');
        return false; // 阻止文件上传
      }
      return true; // 允许文件上传
    }
},

};
</script>

<style>
.container{
  width: 1000px;
  height: 200px;
}
.input-1{
  width: 300px;
  margin-left: 90%;
  position: relative;
  bottom: 45%;
}
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  left: 13%;
  top: 40px;
}
.cover-uploader .el-upload:hover {
  border-color: #8086FE;
}
.des{
  font-size: 20px;
  margin-top: 50px;
  color: #00afff;
  margin-left: 170px;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.cover {
  width: 178px;
  height: 178px;
  display: block;
}
.video{
 width: 100px;
  margin-top: 6%;
  margin-left: 9%;
}
.label{
  position: relative;
  right: 45%;
  top: 30px;
  font-size: 23px;
}
.vbutton{
  margin-left: 48%;
}

</style>
